<script setup lang="ts" name="RoleManager">
import {onActivated, reactive, ref} from 'vue'
import {ElMessage, FormRules} from 'element-plus'
import {
  HeaderData,
  Operation as Oper,
  RowOperbuttons
} from '@/components/dTable/dTable'
import {
  OperButton,
  SearchFromItem,
  SearchButton,
  SearchFromJustify
} from '@/components/dTable/dHeader'
import {
  PageConfig,
  defaultPage,
  defaultPageSize,
  defaultPageSizes,
  defaultLayout
} from '@/components/dTable/dFooter'
import {ColorTheme, ColorRed} from '@/api/config'
import {
  RoleFormInfor,
  getRoleList,
  RoleInfor,
  TableOperation,
  deleteRoles,
  SearchRoleFromData
} from '@/api/baseSetting/roleManager'
import {showMessageBox} from '@/util/element'

import operation from '@/components/dTable/components/operation.vue'
import pageContainer from '@/components/pageContainer.vue'
import dTablePromote from '@/components/dTable/dTablePromote.vue'
import editAuthority from './editAuthority.vue'
import addRoleInfor from './addRoleInfor.vue'

// import {addRoutesByAuth} from '@/router'

type DialogType = 'add' | 'edit'

//数据
const tableData = ref<Array<RoleInfor & RowOperbuttons>>([])

//显示加载状态
const showLoading = ref(false)

//表格数据
const tableHeaderData = ref<Array<HeaderData>>([
  {
    prop: 'author',
    label: '作者名称',
    columnType: 'text',
    align: 'left',
    'min-width': '279'
  },
  {
    prop: 'categoryName',
    label: '书籍类型',
    columnType: 'text',
    align: 'left',
    'min-width': '279'
  },
  {
    prop: 'cover',
    label: '封面图',
    columnType: 'text',
    align: 'left',
    'min-width': '200'
  },
  {
    prop: 'name',
    label: '书籍名称',
    columnType: 'text',
    align: 'left',
    'min-width': '200'
  },
  {
    prop: 'price',
    label: '价格',
    columnType: 'text',
    align: 'left',
    'min-width': '200'
  },
  {
    prop: 'updatedAt',
    label: '更新时间',
    columnType: 'text',
    align: 'left',
    'min-width': '200'
  },
  {
    prop: 'oper',
    label: '操作',
    columnType: 'slot',
    align: 'left',
    width: '80',
    fixed: 'right'
  }
])

//表头
const operButtons = ref<Array<OperButton>>([
  {
    label: '新增',
    type: 'noraml',
    iconConfig: {icon: 'common-add', type: 'custom'},
    code: 'add'
  }
])

//搜索项
const searchFromItems = ref<Array<SearchFromItem>>([
  {
    label: '角色名称',
    placeholder: '请输入角色名称',
    type: 'input',
    prop: 'roleName',
    enterSubmit: true
  }
])

const searchFromData = reactive<SearchRoleFromData>({roleName: null})
const searchFromRules = reactive<FormRules>({
  roleName: [
    {
      required: false,
      message: '长度应不超过20个字符',
      max: 20,
      trigger: ['change', 'blur']
    }
  ]
})

//表单靠左还是靠右
const searchFromJustify = ref<SearchFromJustify>('flexStart')

//搜索按钮配置
const searchButtons = ref<Array<SearchButton>>([
  {type: 'search'},
  {type: 'clear'}
])

//分页配置
const pageConfig = ref<PageConfig>({
  currentPage: defaultPage,
  pageSize: defaultPageSize,
  pageSizes: defaultPageSizes,
  total: 0,
  disabled: false,
  layout: defaultLayout
})

const rowOperButtons: Array<Oper> = [
  {
    code: 'edit',
    label: '编辑',
    iconConfig: {
      icon: 'common-edit',
      type: 'custom',
      color: ColorTheme,
      size: 20
    }
  },
  {
    code: 'delete',
    label: '删除',
    iconConfig: {
      icon: 'common-delete',
      type: 'custom',
      color: ColorRed,
      size: 20
    }
  }
]

//后端数据拼接字段
const setTableData = (data: Array<any>) => {
  const dataArr: Array<RoleInfor & RowOperbuttons> = []
  data.forEach((item) => {
    dataArr.push({...item, oper: rowOperButtons})
  })
  console.log('dataArr', dataArr)

  tableData.value = dataArr
}

//搜索数据
const searchData = (resetPage?: boolean) => {
  showLoading.value = true
  if (resetPage) pageConfig.value.currentPage = 1
  const {roleName} = searchFromData
  getRoleList({
    roleName: roleName,
    page: pageConfig.value.currentPage,
    limit: pageConfig.value.pageSize
  })
    .then((res) => {
      // const {records} = res.data.data
      pageConfig.value.total =
        res.data.data.total === null ? 0 : res.data.data.total
      console.log('res.data.list', res.data.data.list)
      setTableData(res.data.data.list)
    })
    .catch((error) => {
      console.warn(error)
    })
    .finally(() => {
      showLoading.value = false
    })
}

//删除角色
const deleteRole = (ids: Array<string>) => {
  showMessageBox('确认删除选中的角色？')
    .then(() => {
      return deleteRoles(ids)
    })
    .then(() => {
      ElMessage.success('删除成功')
      searchData(true)
      // addRoutesByAuth()
    })
    .catch((error) => {
      console.warn(error)
    })
}

//搜索事件
const onSubmit = () => {
  searchData(true)
}

//清除搜索栏数据
const clearForm = () => {
  searchData(true)
}

//清空搜索表单事件
const onFormClear = () => {
  clearForm()
}

//显示弹窗
const showDialog = ref(false)
// 新增修改角色弹窗
const showRoleDialog = ref(false)
//弹窗类型
const dialogType = ref<DialogType>('add')
const baseRoleFromInfor = {createTime: '', createUserName: '', roleName: ''}
//编辑查看的角色数据
const currRoleFromData = ref<RoleFormInfor>({
  createTime: '',
  roleName: ''
})

//清除数据
const clearDialogData = () => {
  currRoleFromData.value = {...baseRoleFromInfor}
}

//操作按钮事件
const onOperation = (code: TableOperation) => {
  if (code === 'add') {
    clearDialogData()
    dialogType.value = 'add'
    showRoleDialog.value = true
  }
}

const onClose = () => {
  showDialog.value = false
  searchData()
}

const onRoleDialogClose = () => {
  showRoleDialog.value = false
  searchData()
}

//分页尺寸改变事件
const onSizeChange = () => {
  searchData(true)
}

//当前页改变事件
const onCurrentChange = () => {
  searchData()
}

//权限配置
const editAuthorityInfor = (row: RoleInfor) => {
  currRoleFromData.value = {
    roleName: row.roleName,
    remark: row.remark,
    id: row.id,
    menuJson: row.menuJson
  }
  showDialog.value = true
}

//编辑角色信息
const eidtRoleInfor = (row: RoleInfor) => {
  currRoleFromData.value = {
    roleName: row.roleName,
    remark: row.remark,
    id: row.id
  }
  dialogType.value = 'edit'
  showRoleDialog.value = true
}

//操作插槽事件
const cellOperation = (code: string, row: RoleInfor) => {
  if (code === 'authority') {
    editAuthorityInfor(row)
  } else if (code === 'edit') {
    eidtRoleInfor(row)
  } else if (code === 'delete') {
    deleteRole([row.id])
  }
}

onActivated(() => {
  searchData()
})
</script>

<template>
  <page-container>
    <d-table-promote
      :oper-buttons="operButtons"
      :search-form-items="searchFromItems"
      :search-buttons="searchButtons"
      :search-form-data="searchFromData"
      :search-rules="searchFromRules"
      :table-data="tableData"
      :table-header-data="tableHeaderData"
      :page-config="pageConfig"
      :search-from-justify="searchFromJustify"
      :show-loading="showLoading"
      :stripe="true"
      @form-submit="onSubmit"
      @form-clear="onFormClear"
      @operation="onOperation"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
    >
      <template #oper="scope">
        <operation
          :row="scope.row"
          :col="scope.item"
          @opertion-click="cellOperation"
        />
      </template>
    </d-table-promote>
  </page-container>
  <edit-authority
    v-if="showDialog"
    :show-dialog="showDialog"
    :role-data="currRoleFromData"
    @close="onClose"
  />
  <add-role-infor
    v-if="showRoleDialog"
    :show-dialog="showRoleDialog"
    :dialog-type="dialogType"
    :role-data="currRoleFromData"
    @close="onRoleDialogClose"
  />
</template>

<style scoped></style>
